﻿<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="Shortcut Icon" href="../images/aecc.ico" type="image/x-icon" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="../StaticFiles/element-ui/element-ui.css">
  <link rel="stylesheet" href="../StaticFiles/nprogress/nprogress.min.css">
  <link rel="stylesheet" href="../styles/vue-page-common.css">
  <script src="../Scripts/vue.min.js"></script>
  <script src="../StaticFiles/element-ui/element-ui.js"></script>
  <script src="../Scripts/axios.min.js"></script>
  <script src="../StaticFiles/nprogress/nprogress.min.js"></script>
  <script src="../Scripts/dayjs.min.js"></script>
  <script src="../Scripts/axios.config.js"></script>
  <title>热表厂单元技能矩阵维护</title>
  <style>
    .el-form--lable-top .el-form-item__label {
      font-weight: bold;
      padding-bottom: 0 !important;
    }

    .el-form-item {
      margin-bottom: 10px;
    }

    .el-dialog__body {
      padding-top: 10px;
      padding-bottom: 10px;
    }

    .blue {
      color: #409EFF !important;
      font-weight: bold;
    }

    .red {
      color: red !important;
      font-weight: bold;
    }
  </style>
</head>

<body>
  <div id="app" v-cloak v-on:keyup.enter="getData">
    <!-- 报表标题 -->
    <vue2-report-header :title="'热表厂单元技能矩阵维护'"></vue2-report-header>
    <div style="padding: 10px;">
      <!-- 查询条件 -->
      <el-form :inline="true" :model="queryInfo" ref="queryInfoRef" style="margin: 10px" :label-position="'left'">
        <el-form-item label="组织结构:">
          <el-cascader :options="orginazition" :props="{ checkStrictly: true}" ref="orginazitionRef"
            v-model="queryInfo.selectOrg" clearable style="width:400px;">
          </el-cascader>
        </el-form-item>

        <el-form-item label="指标类型:">
          <el-select v-model="queryInfo.skilltype" placeholder="请选择" filterable clearable>
            <el-option v-for="i in skillTypeList" :key="i" :label="i" :value="i">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="指标名称:">
          <el-input v-model.trim="queryInfo.skilltargetname" clearable></el-input>
        </el-form-item>

        <el-form-item label="姓名:">
          <el-input v-model.trim="queryInfo.fullname" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="getData">查询</el-button>
          <el-button type="success" icon="el-icon-circle-plus-outline" size="small" @click="addDialogVisible = true"
            :disabled="!isLegel">增加
          </el-button>
          <el-link icon="el-icon-link" type="primary" style="margin-left: 10px;"
            @click="open('RbSkillTargetMaint.html','热表厂技能指标维护')">热表厂技能指标维护
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table v-loading="loading" v-loading.fullscreen.lock="loading" element-loading-text="数据加载中"
        element-loading-background="rgba(0,0,0,0.8)" :data="dataList" stripe border show-overflow-tooltip>
        <el-table-column type="index" width="40"></el-table-column>
        <el-table-column label="操作" width="130">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="light" content="修改技能矩阵" placement="top-start" :popper-class="'blue'">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"
                :disabled="!isLegel">
              </el-button>
            </el-tooltip>

            <el-tooltip class="item" effect="light" content="删除技能矩阵，请谨慎处理！" placement="top-start" :popper-class="'red'">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteHandler(scope.row.id)"
                :disabled="!isLegel">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="唯一id" prop="id" width="300" v-if="false" show-overflow-tooltip></el-table-column>
        <el-table-column label="指标id" prop="rbskilltargetmaintid" v-if="false" show-overflow-tooltip></el-table-column>
        <el-table-column label="组织架构" prop="orginfo" width="300" show-overflow-tooltip></el-table-column>
        <el-table-column label="指标类型" prop="skilltype" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column label="指标名称" prop="skilltargetname" width="300" show-overflow-tooltip></el-table-column>
        <el-table-column label="员工" prop="workerfullname" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column label="指标执行情况" prop="processvalue" width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.processvalue+'%'}}
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="notes" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建人" prop="createfullname" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间" prop="createdate" width="180" :formatter="replaceDate"></el-table-column>
        <el-table-column label="修改人" prop="lastchangefullname" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column label="修改时间" prop="lastchangedate" width="180" :formatter="replaceDate"></el-table-column>
        <el-table-column label="启用状态" prop="isuse" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isuse" @change="changeStatus(scope.row)" active-text="启用" inactive-text=""
              :disabled="!isLegel">
            </el-switch>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage" :page-sizes="[10,20,50]" :page-size="queryInfo.pageSize"
        layout="prev,pager,next,jumper,sizes,total" :total="total" :disabled="!isLegel">
      </el-pagination>

      <!-- 回到顶部 -->
      <el-backtop></el-backtop>

      <!-- 新增 弹出窗 -->
      <el-dialog title="添加技能矩阵" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose"
        :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form :model="addForm" :rules="formRule" ref="addFormRef" lable-width="100px" :inline="true"
          :label-position="'top'">
          <el-form-item label="组织结构:" prop="selectOrg">
            <el-cascader :options="orginazition" :props="{ checkStrictly: false}" ref="orginazitionRef"
              v-model="addForm.selectOrg" clearable style="width:400px;" @change="selectOrgChange">
            </el-cascader>
          </el-form-item>

          <el-form-item label="指标名称:" prop="rbskilltargetmaintid">
            <el-select v-model="addForm.rbskilltargetmaintid" placeholder="请选择" filterable clearable
              style="width: 400px;">
              <el-option-group v-for="group in skillTargetList" :key="group.label" :label="group.label">
                <el-option v-for="item in group.options" :key="item.id" :label="item.skilltargetname" :value="item.id">
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>

          <el-form-item label="员工:" prop="employeeid">
            <el-select v-model="addForm.employeeid" placeholder="请选择" filterable clearable style="width: 400px;">
              <el-option v-for="i in workerList" :key="i.employeeid" :label="i.fullname" :value="i.employeeid">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="指标执行情况:" prop="processvalue">
            <el-select v-model="addForm.processvalue" placeholder="请选择" filterable clearable style="width: 400px;">
              <el-option v-for="i in processValueList" :key="i.value" :label="i.label" :value="i.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注:" prop="notes">
            <el-input v-model.trim="addForm.notes" style="width: 400px;"></el-input>
          </el-form-item>
        </el-form>
        <!-- 弹出窗底下按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="addItem" size="small" :disabled="addBtnDisabled">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改 弹出窗 -->
      <el-dialog title="修改技能矩阵" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose"
        :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form :model="editForm" :rules="formRule" ref="editFormRef" :inline="true" :label-position="'top'"
          lable-width="100px">
          <el-form-item label="组织结构:" prop="selectOrg">
            <el-cascader :options="orginazition" :props="{ checkStrictly: false}" ref="orginazitionRef"
              v-model="editForm.selectOrg" clearable style="width:400px;" @change="editFormSelectOrgChange">
            </el-cascader>
          </el-form-item>

          <el-form-item label="指标名称:" prop="rbskilltargetmaintid">
            <el-select v-model="editForm.rbskilltargetmaintid" placeholder="请选择" filterable clearable
              style="width: 400px;">
              <el-option-group v-for="group in skillTargetList" :key="group.label" :label="group.label">
                <el-option v-for="item in group.options" :key="item.id" :label="item.skilltargetname" :value="item.id">
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>

          <el-form-item label="员工:" prop="employeeid">
            <el-select v-model="editForm.employeeid" placeholder="请选择" filterable clearable style="width: 400px;">
              <el-option v-for="i in workerList" :key="i.employeeid" :label="i.fullname" :value="i.employeeid">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="指标执行情况:" prop="processvalue">
            <el-select v-model="editForm.processvalue" placeholder="请选择" filterable clearable style="width: 400px;">
              <el-option v-for="i in processValueList" :key="i.value" :label="i.label" :value="i.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注:" prop="notes">
            <el-input v-model.trim="editForm.notes" style="width: 400px;"></el-input>
          </el-form-item>
        </el-form>
        <!-- 弹出窗底下按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="updateItem" size="small" :disabled="updateBtnDiasbled">确 定
          </el-button>
        </span>
      </el-dialog>
    </div>
  </div>

  <script type="module">
    import { getParams, getUserWhiteList } from '../Scripts/hooks/useCommonMethod.js'
    import Vue2ReportHeader from '../Scripts/components/Vue2ReportHeader.js'
    import { getMESOrginazition } from '../Scripts/hooks/fetchAPI.js'
    import { replaceDate } from '../Scripts/hooks/format.js'
    const app = new Vue({
      el: '#app',
      components: { Vue2ReportHeader },
      data: {
        replaceDate,
        loading: false,
        total: 0,
        queryInfo: {
          selectOrg: '',
          skilltargetname: '',
          skilltype: '',
          fullname: '',
          currentPage: 1,//当前页
          pageSize: 10//每页显示条数
        },
        employeeid: '',
        isLegel: true,
        dataList: [],
        addDialogVisible: false,//添加--弹出框默认隐藏
        addForm: { selectOrg: [], rbskilltargetmaintid: '', employeeid: '', processvalue: '', notes: '' },
        editDialogVisible: false,//编辑--弹出框默认隐藏
        editForm: { selectOrg: [], skilltargetname: '', employeeid: '', processvalue: '', notes: '' },
        //表单校验规则
        formRule: {
          selectOrg: [{ required: true, message: '组织结构不能为空', trigger: 'change' }],
          rbskilltargetmaintid: [{ required: true, message: '指标名称不能为空', trigger: 'change' }],
          employeeid: [{ required: true, message: '员工不能为空', trigger: 'change' }],
          processvalue: [{ required: true, message: '指标执行情况不能为空', trigger: 'change' }],
        },
        addBtnDisabled: false,
        updateBtnDiasbled: false,
        orginazition: [],
        baseApi: '../handler/report/RbSkillTargetEmpMaint.ashx',
        processValueList: [
          { label: '0%', value: '0' },
          { label: '25%', value: '25' },
          { label: '50%', value: '50' },
          { label: '75%', value: '75' },
          { label: '100%', value: '100' }
        ],
        workerList: [],
        skillTargetList: [],
        skillTypeList: ['通用类', '实操类', '专用类']
      },
      methods: {
        //查询数据
        async getData() {
          this.loading = true;
          const { data: { data, meta, total } } = await axios.post(`${this.baseApi}?action=getData`, {
            ...this.queryInfo,
            type: 'getData'
          })
          this.loading = false;
          if (meta.status === 500) {
            return this.$message.error(meta.msg);
          }
          this.dataList = data.map(item => {
            return { ...item, isuse: item.isuse === '0' }; //将【启用状态】由字符串变更为布尔值
          })
          this.total = total;
        },
        createGroups(skillTargetList) {
          // 提取所有不重复的 skilltype
          const skillTypes = [...new Set(skillTargetList.map(item => item.skilltype))];

          let groups = [];
          for (const m of skillTypes) {
            groups.push({
              label: m,
              options: skillTargetList.filter(i => i.skilltype === m)
            })
          }
          return groups;
        },
        // 组织结构change事件
        async selectOrgChange(value) {
          this.addForm.rbskilltargetmaintid = '';
          this.addForm.employeeid = '';
          this.addForm.processvalue = '';

          if (value.length !== 3) {
            return;
          }
          const teamid = value[2];

          const [
            { data: { data: skillTargetList } },
            { data: { data: workerList } }
          ] = await Promise.all([
            await axios.post(`${this.baseApi}?action=getSkillTargetInfo`, {
              type: 'getSkillTargetInfo', teamid
            }),
            await axios.post(`${this.baseApi}?action=getTeamEmpList`, {
              type: 'getTeamEmpList', teamid
            })
          ]);

          this.skillTargetList = this.createGroups(skillTargetList);
          this.workerList = workerList;
        },
        // 编辑对话框组织架构变更
        async editFormSelectOrgChange(value) {
          this.editForm.rbskilltargetmaintid = '';
          this.editForm.employeeid = '';
          this.skillTargetList = [];
          this.workerList = [];

          if (value.length !== 3) { return }

          const teamid = value[2];
          const [
            { data: { data: skillTargetList } },
            { data: { data: workerList } }
          ] = await Promise.all([
            await axios.post(`${this.baseApi}?action=getSkillTargetInfo`, {
              type: 'getSkillTargetInfo', teamid
            }),
            await axios.post(`${this.baseApi}?action=getTeamEmpList`, {
              type: 'getTeamEmpList', teamid
            })
          ]);

          this.skillTargetList = this.createGroups(skillTargetList);
          this.workerList = workerList;
        },
        // 显示编辑弹出框
        async showEditDialog(row) {
          const { factoryid, workcenterid, teamid } = row;
          const [
            { data: { data: skillTargetList } },
            { data: { data: workerList } }
          ] = await Promise.all([
            await axios.post(`${this.baseApi}?action=getSkillTargetInfo`, {
              type: 'getSkillTargetInfo', teamid
            }),
            await axios.post(`${this.baseApi}?action=getTeamEmpList`, {
              type: 'getTeamEmpList', teamid
            })
          ]);

          this.skillTargetList = this.createGroups(skillTargetList);
          this.workerList = workerList;

          this.editDialogVisible = true;
          this.editForm = { ...row, selectOrg: [factoryid, workcenterid, teamid] };
        },
        // 删除
        async deleteHandler(id) {
          const confirmResult = await this.$confirm('将永久删除该技能矩阵项, 此操作无法撤销，请确认是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)

          if (confirmResult !== 'confirm') {
            return this.$message.info('已取消删除!')
          }

          const { data: { data, meta, total } } = await axios.post(`${this.baseApi}?action=deleteItem`, { type: 'deleteItem', id });
          if (meta.status === 500) {
            return this.$message.error(meta.msg);
          }

          if (total > 0) {
            this.$message.success('删除成功!');
            this.getData();
          } else {
            return this.$message.error('删除失败!');
          }
        },
        // 更新启用状态
        async changeStatus(row) {
          // 更新启用状态前确认
          const confirmResult = await this.$confirm('是否切换启用状态?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)

          // 取消切换
          if (confirmResult !== 'confirm') {
            row.isuse = !row.isuse;
            return this.$message.info('已取消切换!')
          }

          const { data: { data, meta, total } } = await axios.post(`${this.baseApi}?action=updateStatus`, {
            type: 'updateStatus',
            id: row.id,
            isuse: row.isuse,
            employeeid: this.employeeid
          });

          if (meta.status === 500) {
            return this.$message.error(meta.msg);
          }

          if (total > 0) {
            this.$message.success('启用状态切换成功');
            this.getData();
          } else {
            return this.$message.error('启用状态切换失败');
          }
        },
        // 新增 对话框点击确定
        addItem() {
          this.$refs["addFormRef"].validate(async (valid) => {
            if (valid) {
              // 增加前先判断是否已存在
              const { data: { data: isAlreadyExists } } = await axios.post(`${this.baseApi}?action=isAlreadyExists`, {
                type: 'isAlreadyExists',
                ...this.addForm
              });

              const { rbskilltargetmaintid, employeeid } = this.addForm;

              const skilltargetname = [].concat(...this.skillTargetList.map(group => group.options)).filter(i => i.id === rbskilltargetmaintid)[0].skilltargetname;
              const fullname = this.workerList.filter(i => i.employeeid === employeeid)[0].fullname;

              if (isAlreadyExists) {
                return this.$message.error(`指标【${skilltargetname}】已经维护过员工【${fullname}】，不能重复添加`);
              }

              // 防止重复点击
              this.addBtnDisabled = true;
              const { data: { data, meta, total } } = await axios.post(`${this.baseApi}?action=addItem`, {
                type: 'addItem',
                ...this.addForm,
                createemployeeid: this.employeeid
              });

              if (meta.status === 500) {
                return this.$message.error(meta.msg);
              }

              if (total > 0) {
                this.$message.success('新增成功');
                this.getData();
                this.addDialogVisible = false;
              } else {
                return this.$message.error('新增失败')
              }
            }
          })
        },
        // 编辑 对话框点击确定
        updateItem() {
          this.$refs["editFormRef"].validate(async (valid) => {
            if (valid) {
              const { data: { data: isAlreadyExists } } = await axios.post(`${this.baseApi}?action=isAlreadyExists`, {
                type: 'isAlreadyExists',
                ...this.editForm
              });

              const { rbskilltargetmaintid, employeeid } = this.editForm;
              const skilltargetname = [].concat(...this.skillTargetList.map(group => group.options)).filter(i => i.id === rbskilltargetmaintid)[0].skilltargetname;
              const fullname = this.workerList.filter(i => i.employeeid === employeeid)[0].fullname;

              if (isAlreadyExists) {
                return this.$message.error(`指标【${skilltargetname}】已经维护过员工【${fullname}】，不能重复添加`);
              }

              // 防止重复点击
              this.updateBtnDiasbled = true;
              const { data: { data, meta, total } } = await axios.post(`${this.baseApi}?action=updateItem`, {
                type: 'updateItem',
                ...this.editForm,
                lastchangeemployeeid: this.employeeid
              });

              if (meta.status === 500) {
                return this.$message.error(meta.msg);
              }

              if (total > 0) {
                this.$message.success('修改成功');
                this.getData();
                this.editDialogVisible = false;
              } else {
                this.$message.error('修改失败');
              }
            }
          })
        },
        //新增 弹出框关闭
        addDialogClose() {
          this.$refs["addFormRef"].resetFields();
          this.workerList = [];
          this.skillTargetList = [];
          this.addBtnDisabled = false;
        },
        //编辑 弹出框关闭
        editDialogClose() {
          this.$refs["editFormRef"].resetFields();
          this.updateBtnDiasbled = false;
        },
        //监听 页码值 改变的事件
        handleCurrentChange(newPage) {
          this.queryInfo.currentPage = newPage;
          this.getData();
        },
        //监听 pagesize 改变的事件
        handleSizeChange(newSize) {
          this.queryInfo.pageSize = newSize;
          this.getData();
        },
        // 跳转链接
        async open(pageurl, reportname) {
          this.$confirm(`即将跳转并打开【${reportname}】`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const { origin, search } = window.location;
            let url = `${origin}/MESReport/Baobiao/${pageurl}${search}`;
            window.open(url);
          }).catch(() => {
            this.$message.info('取消跳转');
          });
        }
      },
      async created() {
        if (!getParams("uid")) {
          this.isLegel = false;
          return this.$notify.error({ title: '错误', message: '该用户无权使用该功能!' });
        }
        this.employeeid = getParams("uid");
        this.orginazition = await getMESOrginazition({ isMapping: '是', factoryCode: '602', wctype: '是' });
        // 获取用户权限白名单
        const pageurl = window.location.pathname.split('/')[3];
        const whiteList = await getUserWhiteList(pageurl, this.$message);

        if (whiteList.some(i => i === this.employeeid)) {
          this.isLegel = true;
          this.getData();
        } else {
          this.isLegel = false;
        }
      },
      watch: {
        queryInfo: { handler() { this.queryInfo.currentPage = 1 }, deep: true }
      }
    })
  </script>
</body>

</html>